package com.umer.pinban.customer;

import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.common.base.fragment.BaseFragment;
import com.common.bean.InfoResult;
import com.common.bean.UserInfo;
import com.common.image.ImagePreview;
import com.common.image.bean.ImageInfo;
import com.common.image.view.listener.OnBigImageClickListener;
import com.common.image.view.listener.OnBigImageLongClickListener;
import com.common.image.view.listener.OnBigImagePageChangeListener;
import com.common.image.view.listener.OnOriginProgressListener;
import com.common.okhttp.OkEntityListRequest;
import com.common.ui.loadsir.callback.EmptyCallback;
import com.common.ui.loadsir.callback.ErrorCallback;
import com.common.ui.loadsir.callback.NoNetCallback;
import com.common.ui.recycleview.PullLoadMoreRecyclerView;
import com.common.ui.recycleview.listener.DataStateListener;
import com.common.ui.recycleview.listener.OptListener;
import com.common.utils.Constants;
import com.common.utils.ItemClickSupport;
import com.umer.pinban.AppHolder;
import com.umer.pinban.R;
import com.umer.pinban.adapter.customer.CustomerTailRecordListAdapter;
import com.umer.pinban.bean.PicInfosBean;
import com.umer.pinban.bean.customer.CustomerTailRecordBean;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

public class GenJinFragment extends BaseFragment implements OptListener, DataStateListener,
        PullLoadMoreRecyclerView.PullLoadMoreListener {

    private static int customerId;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.pullLoadMoreRecyclerView)
    PullLoadMoreRecyclerView pullLoadMoreRecyclerView;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    private UserInfo userInfo;
    private CustomerTailRecordListAdapter customerTailRecordListAdapter;
    private List<CustomerTailRecordBean> customerTailRecordBeans = new ArrayList<>();
    private List<ImageInfo> imageInfoList = new ArrayList<>();
    ImagePreview.LoadStrategy loadStrategy = ImagePreview.LoadStrategy.Default;

    public static GenJinFragment newInstance(int argument) {
        customerId = argument;
        return new GenJinFragment();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return llContent;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_customer_gen_jin;
    }

    @Override
    public void init() {
        userInfo = AppHolder.getInstance().getUserInfo();
        initView();
    }

    @Override
    public void loadData() {
        customerTailRecordList();
    }

    private void customerTailRecordList() {
        OkEntityListRequest<CustomerTailRecordBean> request = new OkEntityListRequest<>(R.id.customerTailRecordList,
                Constants.customerTailRecordList, CustomerTailRecordBean.class);
        request.addParams("customerId", customerId);
        request.addParams("page",customerTailRecordListAdapter.getPage());
        request.addParams("pageSize",10);
        request.setHeader(true);
        requestOkhttpEntityList(request);
    }

    @Override
    public void onOptClick(View view, Object object) {
        switch (view.getId()) {
            case R.id.iv:
                PicInfosBean picInfosBean = (PicInfosBean) object;
                imageInfoList = picInfosBean.getImageInfoList();
                int index = picInfosBean.getIndex();
                lookPic(index);
            default:break;
        }
    }

    @Override
    public void onRefresh() {
        customerTailRecordListAdapter.reset();
        loadData();
    }

    @Override
    public void onLoadMore() {
        loadData();
    }

    @Override
    public void onDataState(int flag) {
        //1:没有网络 2:没有数据 3:获取数据失败 4:显示内容
        switch (flag) {
            case 1:
                if (loadService != null) {
                    loadService.showCallback(NoNetCallback.class);
                }
                break;
            case 2:
                if (loadService != null) {
                    loadService.showCallback(EmptyCallback.class);
                }
                break;
            case 3:
                if (loadService != null) {
                    loadService.showCallback(ErrorCallback.class);
                }
                break;
            case 4:
                if (loadService != null) {
                    loadService.showSuccess();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        switch (what) {
            case R.id.customerTailRecordList:
                if(swipeRefreshLayout!=null && swipeRefreshLayout.isRefreshing()){
                    swipeRefreshLayout.setRefreshing(false);
                }
                customerTailRecordBeans = (List<CustomerTailRecordBean>) t.getT();
                customerTailRecordListAdapter.addDataSource(customerTailRecordBeans, t);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {
        switch (what) {
            case R.id.customerTailRecordList:
                if(swipeRefreshLayout!=null && swipeRefreshLayout.isRefreshing()){
                    swipeRefreshLayout.setRefreshing(false);
                }
                showToast(t.getDesc());
                break;
            default:
                break;
        }
    }

    private void initView() {

        pullLoadMoreRecyclerView.init(recyclerView, swipeRefreshLayout);
        customerTailRecordListAdapter = new CustomerTailRecordListAdapter(getActivity(),
                R.layout.activity_customer_tail_record_list_item, pullLoadMoreRecyclerView,
                this, this);
        pullLoadMoreRecyclerView.setAdapterTwo(customerTailRecordListAdapter);
        pullLoadMoreRecyclerView.setOnPullLoadMoreListener(this);
        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary);
        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法

        //单击
        ItemClickSupport.addTo(pullLoadMoreRecyclerView.getRecyclerView())
                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                    }
                });
        //长按
        ItemClickSupport.addTo(pullLoadMoreRecyclerView.getRecyclerView()).setOnItemLongClickListener(new ItemClickSupport.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
                return false;
            }
        });
    }

    private void lookPic(int index){
        ImagePreview.getInstance()
                // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好
                .setContext(getActivity())
                // 从第几张图片开始，索引从0开始哦~
                .setIndex(index)
                //=================================================================================================
                // 有三种设置数据集合的方式，根据自己的需求进行三选一：
                // 1：第一步生成的imageInfo List
                .setImageInfoList(imageInfoList)
                // 2：直接传url List
                //.setImageList(List<String> imageList)
                // 3：只有一张图片的情况，可以直接传入这张图片的url
                //.setImage(String image)
                //=================================================================================================
                // 加载策略，默认为手动模式
                .setLoadStrategy(loadStrategy)
                // 保存的文件夹名称，会在Picture目录进行文件夹的新建。比如："BigImageView"，会在Picture目录新建BigImageView文件夹)
                .setFolderName("BigImageView")
                // 缩放动画时长，单位ms
                .setZoomTransitionDuration(300)
                // 是否启用点击图片关闭。默认启用
                .setEnableClickClose(true)
                // 是否启用下拉关闭。默认不启用
                .setEnableDragClose(true)
                // 是否启用上拉关闭。默认不启用
                .setEnableUpDragClose(true)
                // 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setShowCloseButton(true)
                // 设置关闭按钮图片资源，可不填，默认为库中自带：R.drawable.ic_action_close
                .setCloseIconResId(R.drawable.ic_action_close)
                // 是否显示下载按钮，在页面右下角。默认显示
                .setShowDownButton(true)
                // 设置下载按钮图片资源，可不填，默认为库中自带：R.drawable.icon_download_new
                .setDownIconResId(R.drawable.icon_download_new)
                // 设置是否显示顶部的指示器（1/9）默认显示
                .setShowIndicator(true)
                // 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
                .setErrorPlaceHolder(R.drawable.load_failed)
                // 点击回调
                .setBigImageClickListener(new OnBigImageClickListener() {
                    @Override
                    public void onClick(View view, int position) {

                    }
                })
                // 长按回调
                .setBigImageLongClickListener(new OnBigImageLongClickListener() {
                    @Override
                    public boolean onLongClick(View view, int position) {
                        return false;
                    }
                })
                // 页面切换回调
                .setBigImagePageChangeListener(new OnBigImagePageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override public void onPageSelected(int position) {
                    }

                    @Override public void onPageScrollStateChanged(int state) {
                    }
                })

                //=================================================================================================
                // 设置查看原图时的百分比样式：库中带有一个样式：ImagePreview.PROGRESS_THEME_CIRCLE_TEXT，使用如下：
                .setProgressLayoutId(ImagePreview.PROGRESS_THEME_CIRCLE_TEXT, new OnOriginProgressListener() {
                    @Override public void progress(View parentView, int progress) {
                        // 需要找到进度控件并设置百分比，回调中的parentView即传入的布局的根View，可通过parentView找到控件：
                        ProgressBar progressBar = parentView.findViewById(R.id.sh_progress_view);
                        TextView textView = parentView.findViewById(R.id.sh_progress_text);
                        progressBar.setProgress(progress);
                        String progressText = progress + "%";
                        textView.setText(progressText);
                    }

                    @Override public void finish(View parentView) {

                    }
                })

                // 使用自定义百分比样式，传入自己的布局，并设置回调，再根据parentView找到进度控件进行百分比的设置：
                //.setProgressLayoutId(R.layout.image_progress_layout_theme_1, new OnOriginProgressListener() {
                //    @Override public void progress(View parentView, int progress) {
                //        Log.d(TAG, "progress: " + progress);
                //
                //        ProgressBar progressBar = parentView.findViewById(R.id.progress_horizontal);
                //        progressBar.setProgress(progress);
                //    }
                //
                //    @Override public void finish(View parentView) {
                //        Log.d(TAG, "finish: ");
                //    }
                //})
                //=================================================================================================
                // 开启预览
                .start();
    }

}
